package com.chookss.home.audit.reimbursement;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class BorrowChoiceActivity extends BaseAct {
    //借款选择
    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.common_right_txt)
    TextView common_right_txt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    private BorrowChoiceAdapter adapter;
    private ArrayList<WorkNewEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private View emptyView;
    private TextView tvNone;//空布局;
    private int index = -1;//只能选中一个

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_choice);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        common_title_txt.setText("借款记录");
        common_right_txt.setText("确定");
        common_right_txt.setTextColor(getResources().getColor(R.color.main_color));
        common_right_txt.setVisibility(View.VISIBLE);
        index = getIntent().getIntExtra("index", -1);
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 12f), getResources().getColor(R.color.main_bg)));
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new BorrowChoiceAdapter(R.layout.item_borrow_choice, this, list);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(adapter);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        tvNone.setText("暂无物品");
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("auditCd", "1");//
        map.put("repaymentCd", "0");//
        map.put("type", "2");//3补卡4请假7报销记录8物料  9借款记录10补贴11用章
        map.put("createEmployeeCode", new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<WorkNewEntity>>>() {
        }.getType(), null, Urls.selectBaoxiaoEmpList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<WorkNewEntity>>() {
            @Override
            public void onSuccess(List<WorkNewEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
//                    int old = list.size();
//                    for (int i = 0; i < data.size(); i++) {
//                        if(data.get(i).getAuditStatus().equals("1")&&data.get(i).getParams().getRepaymentCd().equals("0")){
//                            //0 未还款  1还款中  2已还款
//                            list.add(data.get(i));
//                        }
//                    }
//                    adapter.notifyItemRangeChanged(old, list.size() - old);
                    int old = list.size();
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(old, data.size());
                }
                if (list.size() == 0) {
                    isEnd = true;
                    adapter.setEmptyView(emptyView);
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class BorrowChoiceAdapter extends BaseQuickAdapter<WorkNewEntity, BaseViewHolderEx> {
        private Activity context;

        public BorrowChoiceAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<WorkNewEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, WorkNewEntity entity) {
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvTitleType = helper.getView(R.id.tvTitleType);
            TextView tvMoney = helper.getView(R.id.tvMoney);
            TextView tvPost = helper.getView(R.id.tvPost);
            TextView tvGroup = helper.getView(R.id.tvGroup);
            TextView tvInit = helper.getView(R.id.tvInit);
            LinearLayout llMoney = helper.getView(R.id.llMoney);
            LinearLayout llGroup = helper.getView(R.id.llGroup);
            LinearLayout llPost = helper.getView(R.id.llPost);
            ImageView ivStatus = helper.getView(R.id.ivStatus);
            RelativeLayout rlStatus = helper.getView(R.id.rlStatus);
            tvTitle.setText(entity.getCreateEmployeeName()+"的"+entity.getBaoxiaoTypeName()+"申请");
            llMoney.setVisibility(View.VISIBLE);
            tvMoney.setText("借款金额：" + ClearMoreZeroUtil.subZeroAndDot(entity.getAmt()) + "元");
            if (!Utils.isNull(entity.getRepaymentRemark())) {
                tvInit.setText(entity.getRepaymentRemark());
            } else if (!Utils.isNull(entity.getRemark())) {
                tvInit.setText(entity.getRemark());
            } else {
                tvInit.setText("无");
            }
            if (Utils.isNull(entity.getGroupName())) {
                llGroup.setVisibility(View.GONE);
            } else {
                llGroup.setVisibility(View.VISIBLE);
                tvGroup.setText("所属项目组：" + entity.getGroupName());
            }
            if (Utils.isNull(entity.getOrgName())) {
                llPost.setVisibility(View.GONE);
            } else {
                llPost.setVisibility(View.VISIBLE);
                tvPost.setText("所属部门：" + entity.getOrgName());
            }
            if ("1".equals(entity.getAuditCd())) {
                if ("1".equals(entity.getRepaymentCd())) {
                    tvTitleType.setText("还款中");
                    tvTitleType.setTextColor(Color.parseColor("#FCA817"));
                    tvTitleType.setBackgroundResource(R.drawable.shape_fca817_4_1f);
                } else if ("2".equals(entity.getRepaymentCd())) {
                    tvTitleType.setText("已还款");
                    tvTitleType.setTextColor(Color.parseColor("#9A9A9A"));
                    tvTitleType.setBackgroundResource(R.drawable.shape_e5e5e5_4);
                } else {
                    tvTitleType.setText("已借款");
                    tvTitleType.setTextColor(Color.parseColor("#44D3B3"));
                    tvTitleType.setBackgroundResource(R.drawable.shape_44d3b3_4_2f);
                }
            }
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivStatus.getLayoutParams();
            if (index == helper.getItemPosition()) {
                params.height = Utils.dip2px(context, 24);
                params.width = Utils.dip2px(context, 24);
                ivStatus.setBackgroundResource(R.drawable.icon_fx_select);
            } else {
                params.height = Utils.dip2px(context, 14);
                params.width = Utils.dip2px(context, 14);
                ivStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
            }
            ivStatus.setLayoutParams(params);
            rlStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (index == helper.getItemPosition()) {
                        index = -1;
                        adapter.notifyItemChanged(helper.getItemPosition());
                    } else {
                        int oldIndex = -1;
                        if (index >= 0) {
                            oldIndex = index;
                        }
                        index = helper.getItemPosition();
                        adapter.notifyItemChanged(helper.getItemPosition());
                        if (oldIndex >= 0) {
                            adapter.notifyItemChanged(oldIndex);
                        }

                    }

                }
            });
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = new Intent(context, ReimbursementDetailActivity.class);
                    entity.setProjectCode(entity.getBaoxiaoCode());
                    intent.putExtra("data", entity);
                    intent.putExtra("operate", true);
                    intent.putExtra("type",9);
                    context.startActivity(intent);
                }
            });
        }

    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.common_title_back, R.id.common_right_txt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
                Intent intent = new Intent();
                if (index < 0) {
                    intent.putExtra("index", -1);
                } else {
                    WorkNewEntity workNewEntity=list.get(index);
                    workNewEntity.setProjectCode(workNewEntity.getBaoxiaoCode());
                    intent.putExtra("data", workNewEntity);
                    intent.putExtra("index", index);
                }
                setResult(1000, intent);
                finish();
                break;
        }
    }
}
